﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Maps.Controls;
using System.Windows.Data;
using Microsoft.Phone.Maps.Toolkit;
using MapHello.Service;
using Windows.Devices.Geolocation;
using MapHello.Data;
using System.Device.Location;
using MapHello.Basic;
using System.ComponentModel;

namespace MapHello
{
    public partial class MapPage : PhoneApplicationPage
    {
        public MapPage()
        {
            InitializeComponent();

            this.Loaded += OnMapPageLoaded;

            var mapCenterConfig = Service.LoadConfig(Config.MapCenter);
            var zoomLevelConfig = Service.LoadConfig(Config.ZoomLevel);

            if (null != mapCenterConfig && null != zoomLevelConfig)
            {
                var values = mapCenterConfig.Value.Split(',');
                this.map.ZoomLevel = double.Parse(zoomLevelConfig.Value);
                this.map.Center = new GeoCoordinate(double.Parse(values[0]), double.Parse(values[1]));
            }

            this.navigationBar.NavigationItemTappedEvent += navigationBar_NavigationItemTappedEvent;
        }

        void navigationBar_NavigationItemTappedEvent(object sender, string e)
        {
            MessageBox.Show(e);
        }

        private MapHelloService _service;

        private MapHelloService Service
        {
            get
            {
                if (null == _service)
                {
                    _service = new MapHelloService();
                }
                return _service;
            }
        }

        private Pushpin _myPushpin;
        public Pushpin MyPushpin
        {
            get
            {
                if (null == _myPushpin)
                {
                    _myPushpin = MapExtensions.GetChildren(this.map).FirstOrDefault<DependencyObject>(i => i is Pushpin && ((Pushpin)i).Name == "myPushpin") as Pushpin;
                }

                return _myPushpin;
            }
        }


        void OnMapPageLoaded(object sender, RoutedEventArgs e)
        {
            MyPushpin.DataContext = View.Instance.Me;
            View.Instance.PropertyChanged += OnViewPropertyChanged;
            this.map.ZoomLevelChanged += OnMapZoomLevelChanged;

            View.Instance.IsLocationTracked = true;
           
        }

        void OnMapZoomLevelChanged(object sender, MapZoomLevelChangedEventArgs e)
        {
            if (this.map.ZoomLevel >= Utility.MinMapOffsetZoomLevel && this.map.ZoomLevel < Utility.MaxMapOffsetZoomLevel + 1)
            {
                
            }
        }

        void OnViewPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsLocationTracked")
            {
                if (View.Instance.IsLocationTracked)
                {
                    LocationService.GeoLocator.PositionChanged += OnGeoLocatorPositionChanged;
                }
                else
                {
                    LocationService.GeoLocator.PositionChanged -= OnGeoLocatorPositionChanged;
                }
            }
        }

        void OnGeoLocatorPositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            if (sender.LocationStatus == PositionStatus.Ready )
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    double latitude = args.Position.Coordinate.Latitude;
                    double longitude = args.Position.Coordinate.Longitude;

                    // Utility.OffsetMapLocation(ref latitude, ref longitude, 18);

                    View.Instance.Me.Position = new Position()
                    {
                        Latitude = latitude,
                        Longitude = longitude,
                        ModifiedOn = args.Position.Coordinate.Timestamp.DateTime
                    };

                    Service.SavePerson(View.Instance.Me);

                    /*
                    // offset the position
                    Utility.OffsetMapLocation(ref latitude, ref longitude, this.map.ZoomLevel);
                    View.Instance.Me.Position = new Position()
                    {
                        Latitude = latitude,
                        Longitude = longitude,
                        ModifiedOn = args.Position.Coordinate.Timestamp.DateTime
                    };
                     * */
                });


            }
        }

        private void OnMyPushpinTapped(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.map.SetView(MyPushpin.GeoCoordinate, this.map.ZoomLevel);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            Service.SaveConfig(Config.MapCenter, string.Format("{0},{1}", this.map.Center.Latitude, this.map.Center.Longitude), true);
            Service.SaveConfig(Config.ZoomLevel, this.map.ZoomLevel.ToString(), true);
        }

        private void OnFuncButtonHeld(object sender, System.Windows.Input.GestureEventArgs e)
        {
            funcButtonHeldStory.Begin();
        }

        private void OnFuncButtonTapped(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.map.SetView(MyPushpin.GeoCoordinate, this.map.ZoomLevel);
        }
    }
}